import { useRef, useState } from 'react'
import { Group, Layer, Rect, Stage, Transformer } from 'react-konva'

export default function View() {
  const [selectedShape, setSelectedShape] = useState(null)
  const stageRef = useRef(null)
  const groupRef = useRef(null)
  const transformerRef = useRef(null)
  const [groups, setGroups] = useState([
    {
      id: 1,
      type: 'group',
      x: 0,
      y: 0,
      scaleX: 1,
      scaleY: 1,
      children: [
        { id: 2, type: 'rect', x: 0, y: 0, width: 100, height: 100, fill: 'red' },
        {
          id: 3,
          type: 'group',
          x: 0,
          y: 0,
          scaleX: 0.5,
          scaleY: 0.5,
          children: [
            { id: 4, type: 'rect', x: 150, y: 150, width: 50, height: 50, fill: 'yellow' },
            { id: 5, type: 'rect', x: 250, y: 250, width: 150, height: 150, fill: 'green' }
          ]
        }
      ]
    }
  ])

  // 递归渲染函数
  const renderElement = element => {
    if (element.type === 'group') {
      return (
        <Group key={element.id} x={element.x} y={element.y} scaleX={element.scaleX} scaleY={element.scaleY}>
          {element.children.map(child => renderElement(child))}
        </Group>
      )
    } else if (element.type === 'rect') {
      return (
        <Rect
          key={element.id}
          x={element.x}
          y={element.y}
          width={element.width}
          height={element.height}
          fill={element.fill}
        />
      )
    }
    return null
  }

  const handleStageClick = e => {
    // 如果点击的是空白区域，取消选中
    if (e.target === e.target.getStage()) {
      setSelectedShape(null)
      return
    }

    // 如果点击的是矩形，选中它
    if (e.target.nodeType === 'Shape') {
      setSelectedShape(groupRef.current)
    }
  }

  return (
    <Stage width={window.innerWidth} height={window.innerHeight} ref={stageRef} onClick={handleStageClick}>
      <Layer>
        <Group
          ref={groupRef}
          draggable
          onDragEnd={e => {
            console.log('🚀 ~ View ~ e:', e)
          }}
        >
          {groups.map(group => renderElement(group))}
        </Group>

        {selectedShape && (
          <Transformer
            ref={transformerRef}
            boundBoxFunc={(oldBox, newBox) => {
              // 限制最小尺寸
              if (newBox.width < 5 || newBox.height < 5) {
                return oldBox
              }
              return newBox
            }}
            nodes={[selectedShape]}
          />
        )}
      </Layer>
    </Stage>
  )
}
